//
//  KKPhotoGroupViewController.m
//  KKImagePickerController
//
//  Created by Leo on 15/6/24.
//  Copyright (c) 2015年 Juvid. All rights reserved.
//

#import "KKPhotoGroupViewController.h"
#import "KKPhotoListViewController.h"
#import "KKAlertView.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import "KKImagePickerModel.h"

@interface KKPhotoGroupViewController () <UITableViewDataSource, UITableViewDelegate> {
    
    UITableView* _groupTableView;
    UIButton* _cancelButton;
    
    //  Data
    ALAssetsLibrary* _assetsLibrary;
    NSMutableArray* _groupArray;
}

@end

@implementation KKPhotoGroupViewController

- (void)loadView {
    [super loadView];
    UIView* rootView = [self view];
    rootView.backgroundColor = [UIColor whiteColor];
    
    _groupTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height-64)];
    _groupTableView.dataSource = self;
    _groupTableView.delegate = self;
    _groupTableView.rowHeight = 90.0f;
    _groupTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [rootView addSubview: _groupTableView];
    
    {
        _cancelButton = [UIButton buttonWithType: UIButtonTypeCustom];
        _cancelButton.frame = CGRectMake(0, 0, 40, 40);
        _cancelButton.titleLabel.font = [UIFont systemFontOfSize: 16.0];
        [_cancelButton setTitle: @"取消" forState: UIControlStateNormal];
        [_cancelButton setTitleColor: [UIColor blackColor] forState: UIControlStateNormal];
        [_cancelButton setTitleColor: [UIColor lightGrayColor] forState: UIControlStateHighlighted];
        [_cancelButton addGestureRecognizer: [[UITapGestureRecognizer alloc] initWithTarget: self action: @selector(onTap:)]];
        
        {
            UIBarButtonItem* rightButtonItem = [[UIBarButtonItem alloc] initWithCustomView: _cancelButton];
            UIBarButtonItem* spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem: UIBarButtonSystemItemFixedSpace target: nil action: nil];
            spaceItem.width = -8;
            
            self.navigationItem.rightBarButtonItems = @[spaceItem,rightButtonItem];
        }
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"照片";
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]}];
    [self loadAssetsGroupFromLibrary];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UIGestureRecognizer methods

- (void)onTap:(UITapGestureRecognizer*)tapper {
    UIView* target = tapper.view;
    if (target == _cancelButton) {
        
        [[NSNotificationCenter defaultCenter] postNotificationName: KKImagePickerControllerNotificationActionOfSend object: nil];
        return;
    }
}

#pragma mark - Private methods

- (void)loadAssetsGroupFromLibrary {
    
    _assetsLibrary = [ALAssetsLibrary new];
    _groupArray = [NSMutableArray array];
    
    __weak ALAssetsLibrary* weakAssetsLibrary = _assetsLibrary;
    __weak NSMutableArray* weakGroupArray = _groupArray;
    __weak UITableView* weakTableView = _groupTableView;
    
    ALAssetsLibraryGroupsEnumerationResultsBlock listGroupResultsBlock = ^(ALAssetsGroup *group, BOOL *stop) {
        
        if (group && [group numberOfAssets] != 0) {
            
            if ([[group valueForProperty: ALAssetsGroupPropertyType] integerValue] == ALAssetsGroupSavedPhotos) {
                [weakGroupArray insertObject: group atIndex: 0];
            }
            else {
                [weakGroupArray addObject: group];
            }
        }
        else {
            dispatch_async(dispatch_get_main_queue(), ^{
               [weakTableView reloadData];
            });
        }
    };
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        
        [weakAssetsLibrary enumerateGroupsWithTypes: ALAssetsGroupAll usingBlock: listGroupResultsBlock failureBlock:^(NSError *error) {
            NSLog(@"Group not found!\n");
//            UIAlertView *aleter=[[UIAlertView alloc]initWithTitle:@"提示" message:@"暂无权限，请在设置项中打开权限" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
//            [aleter show];
            [[KKAlertView shareInterce] showWithTitle: @"提示" andWithMessage: @"暂无权限，请在设置项中打开权限" andWithCancelTitle: nil andWithCancelHandle: nil andWithSureTitle: @"关闭" andWithSureHandle: nil];
        }];
    });
}

#pragma mark - UITableView methods

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _groupArray.count;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString* identifier = @"Group";
    
    KKPhotoGroupCell* cell = [tableView dequeueReusableCellWithIdentifier: identifier];
    if (cell == nil) {
        cell = [[KKPhotoGroupCell alloc] initWithStyle: UITableViewCellStyleDefault reuseIdentifier: identifier];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    
    ALAssetsGroup* assetsGroup = _groupArray[indexPath.row];
    cell.itemImageView.image = [UIImage imageWithCGImage: assetsGroup.posterImage];
    
    NSString* groupName = [assetsGroup valueForProperty: ALAssetsGroupPropertyName];
    NSInteger numberOfAssets = [assetsGroup numberOfAssets];
    
    cell.groupNameLabel.text = [NSString stringWithFormat: @"%@ (%@)", groupName, @(numberOfAssets)];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    ALAssetsGroup* assetsGroup = _groupArray[indexPath.row];
    
    KKPhotoListViewController* listViewController = [KKPhotoListViewController new];
    listViewController.assetsGroup = assetsGroup;
    [self.navigationController pushViewController: listViewController animated: YES];
}

@end


#pragma mark -
#pragma mark - 

@implementation KKPhotoGroupCell

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle: style reuseIdentifier: reuseIdentifier];
    if (self) {
        
        UIView* contentView = [self contentView];
        _itemImageView = [[UIImageView alloc] initWithFrame: CGRectMake(5, 5, 80, 80)];
        [contentView addSubview: _itemImageView];
        
        _groupNameLabel = [[UILabel alloc] initWithFrame: CGRectMake(90, 30, 200, 30)];
        _groupNameLabel.backgroundColor = [UIColor clearColor];
        _groupNameLabel.textAlignment = NSTextAlignmentLeft;
        [contentView addSubview: _groupNameLabel];
        
        UIView* lineView = [[UIView alloc] initWithFrame: CGRectMake(15, CGRectGetHeight(contentView.bounds) - 1, CGRectGetWidth(contentView.bounds) - 15, 1)];
        lineView.backgroundColor = [UIColor colorWithRed: 240./255.0 green: 240./255.0 blue: 240./255.0 alpha: 1.0];
        lineView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin;
        [contentView addSubview: lineView];
    }
    return self;
}

@end
